package org.lk.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.lk.reggie.common.R;
import org.lk.reggie.entity.User;
import org.lk.reggie.service.UserService;
import org.lk.reggie.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController
{
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody Map user)
    {
        String phone = user.get("phone").toString();
        // 调用方法
        // 从 redis 中获取验证码
        //String code = (String) request.getSession().getAttribute((String)user.get("phone"));
        String code = (String) redisTemplate.opsForValue().get(phone);

        System.out.println(code);

        if (code.equals(user.get("code")))
        {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User :: getPhone, user.get("phone"));
            User byId = userService.getOne(queryWrapper);
            if (byId == null)
            {
                log.info("新增用户：{}", user.get("phone") );
                byId = new User();
                byId.setPhone(phone);
                userService.save(byId);
            }
            request.getSession().setAttribute("user", byId.getId());

            // 登录成功，删除验证码
            redisTemplate.delete(phone);
            return R.success(byId);
        }


        return R.error("error");
    }


    @PostMapping("/sendMsg")
    public R<String> sendMessage(@RequestBody User user, HttpServletRequest request)
    {
        // 获取手机号
        String phone = user.getPhone();
        if(phone != null && phone != "")
        {
            // 发送验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            System.out.println("验证码为：" + code);
            // 将生成的验证码保存
            //request.getSession().setAttribute(phone, code);
            // 将生成的验证码保存到 redis 中，并设置有效期为 5 分钟
            redisTemplate.opsForValue().set(phone, code, 500, TimeUnit.SECONDS);

            String is = (String) redisTemplate.opsForValue().get(phone);
            System.out.println(is);
            return R.success("已成功发送，请及时查看");
        }
        return R.error("发送失败");
    }

}
